<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';
import type { TreeData, TreeInstance } from 'element-plus';
import { fetchGetPermTree } from '@/service/api';
import { useLoading } from '~/packages/hooks';

defineOptions({ name: 'PermTreeSelect' });

const props = defineProps<{
  update: number;
}>();

const treeSelectRef = ref<TreeInstance | null>(null);
const treeData = ref<TreeData>([]);

const { loading, startLoading, endLoading } = useLoading();

onMounted(async () => {
  await getPermTree();
});

watch(
  () => props.update,
  async () => {
    await getPermTree();
  }
);

async function getPermTree() {
  try {
    startLoading();
    const { data, error } = await fetchGetPermTree();
    if (!error && data) {
      treeData.value = data;
    }
  } finally {
    endLoading();
  }
}

const model = defineModel<CommonType.IdType[]>('modelValue', {
  default: []
});
</script>

<template>
  <ElTreeSelect
    v-if="!loading"
    ref="treeSelectRef"
    v-model="model"
    :data="treeData"
    node-key="value"
    :empty-values="['']"
    value-on-clear=""
    show-checkbox
    check-strictly
    check-on-click-node
    clearable
    multiple
    collapse-tags
    collapse-tags-tooltip
  />
</template>

<style scoped lang="scss"></style>
